<template>
    <el-form :model="form" :rules="rules" ref="userForm" label-width="120px" v-loading="loading">
        <el-form-item label="真实姓名" prop="real_name">
            <el-input v-model="form.real_name" placeholder="请输入真实姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>

        <el-form-item label="账号" prop="username">
            <el-input v-model="form.username" placeholder="请输入账号"></el-input>
        </el-form-item>

        <el-form-item label="权限" prop="permission">
            <el-select v-model="selectPermission" placeholder="请选择权限">
                <el-option v-for="option in permissionOptions" :key="option.value" :label="option.label"
                    :value="option.value">
                </el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="密码" prop="password" v-if="!isEditMode">
            <el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
        </el-form-item>

        <el-form-item style="margin-top: 1rem;">
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button @click="onReset">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { computed, reactive, ref, watch, watchEffect } from 'vue'
import { handleError } from '@/utils/handleError'
import { useRoute } from 'vue-router'
import { createUserApi, getUserListApi, updateUserApi } from '@/api/user'
import { addRoleApi, updateRoleApi, updatePermissionApi, getRoleApi } from '@/api/auth'
import { getRolePermissions } from '@/utils/permissions'
import { sha256 } from '@/utils/sha256'
import { useCompanyStore } from '@/stores/company'
import { useUserStore } from '@/stores/userinfo'
const route = useRoute()
const companyStore = useCompanyStore()
let loading = ref(false)

// 获取单位ID
const getCompanyId = () => {
    return route.query.id ? Number(route.query.id) : companyStore.currentCompany.id
}

// 定义权限选项
const permissionOptions = computed(() => {
    return useUserStore().role === 'admin' ? [
        { value: 'admin', label: '平台管理员' },
        { value: 'companyAdmin', label: '单位管理员' },
        { value: 'normalUser', label: '普通用户' },
    ] : [
        { value: 'normalUser', label: '普通用户' },
        { value: 'companyAdmin', label: '单位管理员' },
    ]
})
const selectPermission = ref('normalUser')

// 定义表单数据
const form = reactive({
    id: null,
    phone: '',
    email: '',
    username: '',
    company_id: getCompanyId(),
    real_name: '',
    password: '',
    permission: selectPermission.value  // 确保初始化时权限字段与 selectPermission 绑定
})

// 同步 selectPermission 到 form.permission
watch(selectPermission, (newPermission) => {
    form.permission = newPermission
})

const rules = {
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
    ],
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' },
    ],
    permission: [
        { required: true, message: '请选择权限', trigger: 'change' }
    ],
    real_name: [
        { required: true, message: '请输入真实姓名', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
    ]
}

// 获取表单引用
const userForm = ref(null)
// 是否为编辑模式
const isEditMode = ref(false)
const emit = defineEmits(['fetchUser'])
// 接收props
const props = defineProps(['currentUser'])

// 更新用户角色和权限
const updateUserRoleAndPermissions = async (username) => {
    try {
        const parmas = {
            user_name: username,
            company_id: getCompanyId(),
            role_name: selectPermission.value
        }
        // 根据是否为编辑模式选择不同的API
        if (isEditMode.value) {
            // 更新角色
            await updateRoleApi(parmas)
        } else {
            // 添加角色
            await addRoleApi(parmas)
        }
        // 获取对应角色的权限列表
        const permissions = getRolePermissions(selectPermission.value)
        // 获取对应的角色id
        const res = await getUserListApi({
            username: '%' + username + '%',
        })
        const user_id = res.results[0].id
        // 更新权限
        await updatePermissionApi({
            user_id: user_id,
            permissions: permissions,
        })
    } catch (error) {
        handleError(error, '更新角色和权限失败！')
    }
}

// 重置表单
const onReset = () => {
    form.id = null
    form.permission = 'normalUser' // 默认权限
    form.company_id = getCompanyId()
    form.real_name = ''
    form.password = ''
    form.phone = ''
    form.email = ''
    form.username = ''
    selectPermission.value = 'normalUser' // 默认选项
}

// 监听route.query和props变化并设置表单
watchEffect(async () => {
    form.company_id = getCompanyId()
    if (props.currentUser) {
        isEditMode.value = true
        form.id = props.currentUser.id
        form.username = props.currentUser.username
        try {
            loading.value = true
            const userData = await getUserListApi({
                username: props.currentUser.username,
                company_id: form.company_id
            })
            Object.assign(form, userData.results[0])
            // 请求角色
            let res = await getRoleApi({
                username: props.currentUser.username,
            })

            if (res.data && res.data.length === 1) {
                selectPermission.value = res.data[0]
                form.permission = selectPermission.value // 确保同步
            }
        } catch (error) {
            handleError(error, '获取用户信息失败！')
        } finally {
            loading.value = false
        }
    } else {
        isEditMode.value = false
        onReset()
    }
})

// 提交表单
const onSubmit = async () => {
    userForm.value.validate(async (valid) => {
        if (valid) {
            loading.value = true
            try {
                // 手动将 selectPermission 的值赋给 form.permission
                form.permission = selectPermission.value

                if (form.password) {
                    form.password = await sha256(form.password)
                }

                if (form.id) {
                    // 更新用户
                    await updateUserApi(form)
                    // 更新用户角色和权限
                    await updateUserRoleAndPermissions(form.username)
                    ElMessage.success('更新成功！')
                } else {
                    try {
                        // 添加用户
                        await createUserApi(form)
                        // 更新新用户的角色和权限
                        await updateUserRoleAndPermissions(form.username)
                        ElMessage.success('添加成功！')
                    } catch (error) {
                        if (error.message === '用户已存在') {
                            handleError(error, '用户已存在！')
                        }
                        handleError(error, '添加用户出错！')
                    }
                }

                emit('fetchUser')
                userForm.value.resetFields()
            } catch (error) {
                ElMessage.error(error.message || '提交失败！')
            } finally {
                loading.value = false
            }
        } else {
            ElMessage.error('请检查表单填写是否正确')
            loading.value = false
            return false
        }
    })
}
</script>
